using System.Collections.Generic;
using System.Linq;

namespace TicTacToe
{
    internal static class CellHelpers
    {
        /// <summary>
        /// Returns true if every cell in the supplied collection has a value, and those values are all the same.
        /// </summary>
        internal static bool AllCellsArePopulatedAndMatch(this IEnumerable<Cell> cells)
        {
            return CellsMatch(cells, true);
        }

        /// <summary>
        /// Returns true if the supplied collection has exactly one cell with a null symbol.
        /// </summary>
        internal static bool HasOneSpace(this IEnumerable<Cell> cells)
        {
            return cells.CountSpaces() == 1;
        }
        
        /// <summary>
        /// Returns true if every cell which has a value in the supplied collection has the same value.
        /// </summary>
        internal static bool AllPopulatedCellsMatch(this IEnumerable<Cell> cells)
        {
            return CellsMatch(cells, false);
        }

        private static int CountSpaces(this IEnumerable<Cell> cells)
        {
            return cells.Count(s => !s.Symbol.HasValue);
        }

        private static bool CellsMatch(this IEnumerable<Cell> cells, bool includeEmptyCells)
        {
            Symbol? comparison = null;

            foreach (var cell in cells)
            {
                if (!cell.Symbol.HasValue)
                {
                    if (includeEmptyCells)
                        return false;                    
                    
                    continue;
                }

                if (!comparison.HasValue)
                {
                    comparison = cell.Symbol;
                }
                else if (cell.Symbol != comparison)
                {
                    return false;
                }
            }

            return true;
        }
    }
}